package cn.le.springAnnotationCustomize.context;

import cn.le.springAnnotationCustomize.annotation.CustomerRule;
import cn.le.springAnnotationCustomize.annotationUtil.CustomerValidatorRule;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.annotation.Annotation;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by admin on 2017/3/30.
 *
 * 在spring配置文件中配置ApplicationContextAware接口的实现类,spring容器会在加载完spring容器后把上下文对象
 * 调用这个对象中setApplicationContext方法
 *
 * 这里用来加载自定义的注解处理对象
 *
 */
public class CustomerValidatorConfig implements ApplicationContextAware{

    private Map<Annotation,CustomerValidatorRule> rules = new ConcurrentHashMap<Annotation, CustomerValidatorRule>();
    Map<String,Object> customerValidationRules = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        //getBeansWithAnnotation返回带有指定注解类型的bean对象
        customerValidationRules = applicationContext.getBeansWithAnnotation(CustomerRule.class);
        System.out.println(customerValidationRules);
    }

    /**
     * 返回其解析注解的对象
     * @param annotation
     * @return
     */
    private CustomerValidatorRule findFormMap(Annotation annotation)
    {
        System.out.println(annotation);
        for (Map.Entry<String, Object> entry : customerValidationRules.entrySet()) {
            //annotation类型为DateString,这里利用support返回为true,返回CustomerValidatorRule处理对象
            if (entry.getValue() != null && ((CustomerValidatorRule) entry.getValue()).support(annotation)) {
                return (CustomerValidatorRule) entry.getValue();
            }
        }
        return null;
    }

    /**
     * 获取解析验证注解的对象
     * @param annotation
     * @return
     */
    public CustomerValidatorRule findRule(Annotation annotation) {
        //判断是否有此注解类型对象
        if (!rules.containsKey(annotation)) {
            CustomerValidatorRule cvr = findFormMap(annotation);
            if (cvr != null) {
                rules.put(annotation, cvr);
            }
        }
        return rules.get(annotation);
    }
}
